Reading/Writing Binary Files

Saving data as a binary file has several advantages: smaller size compared to text files for the same content; unreadable in text editors (acts as a simple encryption); and you can use a custom extension.

Creating a Binary File and Writing Data

[Excel VBA] Use Open … For Binary Access Write to save data as a binary file. Example: save a line segment’s start (10,10) and end (100,200) coordinates to test.cad.

code.vba
Sub SaveToBinary()
    Dim intFileNum As Integer
    Dim strFile As String
    Dim varText As Variant

    strFile = "D:\test.cad"
    varText = "10 10 100 200"   'Line segment(10,10)-(100,200)
    intFileNum = FreeFile()

    If strFile <> "" Then
        Open strFile For Binary Access Write As #intFileNum
        Put #intFileNum, 1, varText
    End If

    Close #intFileNum
End Sub

Running this saves the coordinate data in binary format to test.cad.

[Python] Use open() with a mode containing b (binary), or use the struct module.

Table 3-5 Mode settings for binary files

Mode Description
rb Open binary file for reading only
rb+ Open binary file for reading and writing
wb Open binary file for writing only; overwrites if exists; creates if not
wb+ Open binary file for reading and writing; overwrites if exists; creates if not
ab Open binary file for appending; adds after existing content if exists; creates if not
ab+ Open binary file for appending and reading; same as ab

Binary files store data in bytes. Convert strings to bytes with bytes() before writing, and decode after reading.

Example using open():

code.python
>>> f = open('D:\\test.cad', 'wb')
>>> f.write(bytes('10 10 100 200', 'utf-8'))
>>> f.close()

Using struct:

code.python
>>> from struct import *
>>> f = open('D:\\test2.cad', 'wb')
>>> f.write(pack('iiii', 10, 10, 100, 200))
>>> f.close()

Reading Binary Files

[Excel VBA] Use Open … For Binary Access Read and Get to read binary data.

code.vba
Sub OpenBinary()
    Dim intFileNum As Integer
    Dim varText As Variant
    Dim strFile As String

    strFile = "D:\test.cad"
    intFileNum = FreeFile()

    If strFile <> "" Then
        Open strFile For Binary Access Read As #intFileNum
        Get #intFileNum, 1, varText
        Debug.Print varText
    End If

    Close #intFileNum
End Sub

[Python] Read binary data, decode, and parse:

code.python
>>> f = open('D:\\test.cad', 'rb')
>>> ln = f.read().decode('utf-8')
>>> f.close()
>>> dt = ln.split(' ')
>>> x1 = int(dt[0](@ref)
>>> y1 = int(dt[1](@ref)

Using struct.unpack():

code.python
>>> f = open('D:\\test2.cad', 'rb')
>>> (a, b, c, d) = unpack('iiii', f.read())
>>> print(a, b, c, d)
10 10 100 200
>>> type(a)
<class 'int'>